//
// Created by ayer on 2025/3/19.
// 来自b站up 天天写乱码 https://space.bilibili.com/193137215
// 跟学手敲
//

#include <iostream>
// #include <string>
#include <cstring>
#include <cerrno>
#include <stdexcept>
#ifdef _WIN32
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif

using namespace std;

int main () {
    // 1.创建socket
    int sockfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sockfd < 0) {
        printf("creeate socket error: error=%d errmsg=%s\n", errno, strerror(errno));
        return 1;
    }
    else {
        printf ("create socket success !\n");
    }

    // 2.绑定socket
    string ip = "127.0.0.1";
    int port = 9080;
    struct  sockaddr_in sockaddr;
    std::memset(&sockaddr, 0, sizeof(sockaddr));
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_addr.s_addr = inet_addr(ip.c_str());
    sockaddr.sin_port = htons(port);
    if (::bind(sockfd, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0) {
        printf("socket bind error: errno=%d errmsg=%s\n", errno, strerror(errno));
        return 1;
    }
    {
        printf("socket bind success: ip=%s port=%d\n",ip.c_str(), port);
    }
    // 3.监听 socket
    if (::listen(sockfd, 1024) < 0) {
        printf("socket listen error: errno=%d errmsg=%s\n", errno, strerror(errno));
        return 1;
    }
    else{
        printf("socket listening ...\n");
    }
    while (true) {
        //4.接受客户端连接
        int connfd = ::accept(sockfd, nullptr, nullptr);
        if (connfd < 0){
            printf("socket accept error: errno=%d errmsg=%s\n", errno, strerror(errno));
            return 1;
        }
        char buf[1024] = {0};
        
        //5.接受客户端的数据
        size_t len = ::recv(connfd, buf, sizeof(buf), 0);
        printf("recv: connfd=%d msg=%s", connfd, buf);
        //6.向客户端发送数据
        ::send(connfd, buf, len, 0);
    }
    //7.关闭socket
    ::close(sockfd);
    return 0;

}